package com.hanxiaozhang.no3algorithm;

/**
 * 〈一句话功能简述〉<br>
 * 〈反向单链表〉
 *
 * @author hanxinghua
 * @create 2022/7/7
 * @since 1.0.0
 */
public class No6ReverseSinglyNode {


    public static void main(String[] args) {

        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        head.next.next.next.next.next = new Node(6);

        head = reverse(head);
        System.out.println("----------");
        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        }

    }


    /**
     * 思路是，从head的后继节点开始，把指针指向前继
     *
     * @param head
     * @return
     */
    public static Node reverse(Node head) {

        if (head == null || head.next == null) {
            return head;
        }
        // 当前的前继节点，当前的后继节点,当前节点
        Node pre = null, next = null, cur = head;

        // 循环遍历当前节点
        while (cur != null) {
            // 获取当前节点的后继节点,临时保存
            next = cur.next;
            // 当前节点的后继节点，指向前继节点
            cur.next = pre;
            // 前继节点，赋值当前节点
            pre = cur;
            // 当前节点，赋值下一个节点
            cur = next;
        }
        return pre;

    }

}


class Node<T> {

    public T data;
    public Node<T> next;


    public Node(T data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Node(T data) {
        this.data = data;
    }

}